//
//  SNPreviewImageView.swift
//  SNVIPER
//
//  Created by shaofeng on 2017/5/19.
//  Copyright © 2017年 shaofeng. All rights reserved.
//

import UIKit
import SNExtensions
import Kingfisher

public typealias SingleTapGestureBlock = () ->();

class SNPreviewImageView: UIView, UIScrollViewDelegate {
    
    var singleTapGestureBlock: SingleTapGestureBlock?;
    
    override init(frame: CGRect) {
        super.init(frame: frame);

        self.scrollView.frame = CGRect(x: 10, y: 0, width: self.bounds.size.width - 20, height: self.bounds.size.height);
        self.scrollView.delegate = self;
        self.addSubview(self.scrollView);
        
        scrollView.addSubview(self.imageContainerView);
        
        imageContainerView.addSubview(self.imageView);
        

        let singleTap = UITapGestureRecognizer(target: self, action: #selector(singleTap(tap:)));
        self.addGestureRecognizer(singleTap);
        
        let doubleTap = UITapGestureRecognizer(target: self, action: #selector(doubleTap(tap:)));
        doubleTap.numberOfTapsRequired = 2;
        singleTap.require(toFail: doubleTap);
        self.addGestureRecognizer(doubleTap);
    }
    
    required init?(coder aDecoder: NSCoder) {
        fatalError("init(coder:) has not been implemented")
    }

    func recoverSubviews() {
        self.scrollView.setZoomScale(1.0, animated: false);
        self.resizeSubviews();
    }
    
    func resizeSubviews() {
        imageContainerView.setOrigin(origin: .zero);
        
        imageContainerView.setWidth(width: self.scrollView.bounds.size.width);
        
        let limage = imageView.image;
        
        if let image = limage {
            if (image.size.height / image.size.width > self.bounds.size.height / self.scrollView.bounds.size.width) {
                imageContainerView.setHeight(height: floor(image.size.height / (image.size.width / self.scrollView.bounds.size.width)));
            }
            else {
                var height = image.size.height / image.size.width * self.scrollView.bounds.size.width;
            
                if (height < 1 || height.isNaN) {
                    height = self.bounds.size.height;
                }
                else {
                    height = floor(height);
                }
                
                imageContainerView.setHeight(height: height);
                imageContainerView.setCenterY(y: self.bounds.size.height / 2);
            }
        }
        if (imageContainerView.bounds.size.height > self.bounds.size.height && imageContainerView.bounds.size.height - self.bounds.size.height <= 1) {
            imageContainerView.setHeight(height: self.bounds.size.height);
        }
        
        let contentSizeH = max(imageContainerView.bounds.size.height, self.bounds.size.height);
        scrollView.contentSize = CGSize(width: scrollView.bounds.size.width, height: contentSizeH);
        scrollView.scrollRectToVisible(self.bounds, animated: true);
        scrollView.alwaysBounceVertical = imageContainerView.bounds.size.height <= self.bounds.size.height ? false : true;
        imageView.frame = imageContainerView.bounds;

    }
        
    @objc func singleTap(tap: UITapGestureRecognizer) {
        
        if let block = self.singleTapGestureBlock {
            block();
        }
    }
    
    @objc func doubleTap(tap: UITapGestureRecognizer) {
        
        if scrollView.zoomScale > 1.0 {
            scrollView.contentInset = .zero;
            scrollView.setZoomScale(1.0, animated: true);
        }
        else {
            let touchPoint = tap.location(in: self.imageView);
            let newZoomScale = scrollView.maximumZoomScale;
            let xsize = self.frame.size.width / newZoomScale;
            let ysize = self.frame.size.height / newZoomScale;
            scrollView.zoom(to: CGRect(x: touchPoint.x - xsize/2, y: touchPoint.y - ysize/2, width: xsize, height: ysize), animated: true);
        }
    }
    
    // MARK:
    
    func viewForZooming(in scrollView: UIScrollView) -> UIView? {
        return imageContainerView;
    }
    
    func scrollViewWillBeginZooming(_ scrollView: UIScrollView, with view: UIView?) {
        scrollView.contentInset = .zero;
    }
    
    func scrollViewDidZoom(_ scrollView: UIScrollView) {
        self.refreshImageContainerViewCenter();
    }
    
    func scrollViewDidEndZooming(_ scrollView: UIScrollView, with view: UIView?, atScale scale: CGFloat) {
        
    }
    
    func refreshImageContainerViewCenter() {
        let offsetX = (scrollView.bounds.width > scrollView.contentSize.width) ? ((scrollView.bounds.width - scrollView.contentSize.width) * 0.5) : 0.0;
        let offsetY = (scrollView.bounds.height > scrollView.contentSize.height) ? ((scrollView.bounds.height - scrollView.contentSize.height) * 0.5) : 0.0;
        imageContainerView.setCenter(x: scrollView.contentSize.width * 0.5 + offsetX, y: scrollView.contentSize.height * 0.5 + offsetY)
    }
    
    var _allowCrop: Bool = false;
    
    var allowCrop: Bool {
        get {
            return _allowCrop;
        }
        
        set {
            _allowCrop = newValue;
            scrollView.maximumZoomScale = newValue ? 4.0 : 2.5;
        }
    }
    
    var _cropRect: CGRect = CGRect.zero;
    
    var cropRect: CGRect {
        get {
            return _cropRect;
        }
        
        set {
            _cropRect = newValue;
        }
    }
    
    func setImageUrl(url:String) {
        scrollView.setZoomScale(1.0, animated: false);
        let urll = URL(string: url);
        imageView.kf.setImage(with: urll, placeholder: nil, options: nil, progressBlock: nil) { (image, error, cacheType, url) in
            self.resizeSubviews();
        }
    }
    
    var imageView: UIImageView = {
        let i = UIImageView();
        i.backgroundColor = UIColor(white: 1.0, alpha: 0.5);
        i.contentMode = .scaleAspectFill;
        i.clipsToBounds = true;
        return i;
    }();
    
    var scrollView: UIScrollView = {
        let s = UIScrollView();
        s.bouncesZoom = true;
        s.maximumZoomScale = 2.5;
        s.minimumZoomScale = 1.0;
        s.isMultipleTouchEnabled = true;
        s.scrollsToTop = false;
        s.showsHorizontalScrollIndicator = false;
        s.showsVerticalScrollIndicator = true;
        s.autoresizingMask = UIViewAutoresizing(rawValue: UIViewAutoresizing.flexibleWidth.rawValue | UIViewAutoresizing.flexibleHeight.rawValue);
        s.delaysContentTouches = false;
        s.canCancelContentTouches = true;
        s.alwaysBounceVertical = false;
        return s;
    }();
    
    var imageContainerView: UIView = {
        let i = UIView();
        i.clipsToBounds = true;
        i.contentMode = .scaleAspectFill;
        return i;
    }();
}
